package com.atguigu.daijia.common.login;


import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import feign.Request;
import jakarta.servlet.http.HttpServletRequest;
import jdk.jfr.Category;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCommand;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.filter.RequestContextFilter;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

@Component
@Aspect //切面类
public class GuiguLoginAspect {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Around("execution(* com.atguigu.daijia.*.controller.*.*(..)) && @annotation(guigulogin) ")
    public Object login(ProceedingJoinPoint proceedingJoinPoint, GuiguLogin guigulogin) throws Throwable{
        //获取请求头
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) attributes;
        HttpServletRequest request = sra.getRequest();

        //获取token
        String token = request.getHeader("token");
        //判断token
        if (!StringUtils.hasText(token)){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //查询redis
        String userId = stringRedisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);

        if (StringUtils.hasText(userId)){
            AuthContextHolder.setUserId(Long.parseLong(userId));
        }
        return proceedingJoinPoint.proceed();
    }
}
